package com.ja.sevice.impl;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.ja.config.WebsiteStateConfig;
import com.ja.dao.AgencyCenterMapper;
import com.ja.dao.DamalMapper;
import com.ja.dao.LuckyCountMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.AgentLink;
import com.ja.domain.Damal;
import com.ja.domain.LuckyCount;
import com.ja.domain.Order;
import com.ja.domain.PagingData;
import com.ja.domain.User;
import com.ja.sevice.AgencyCenterSevice;
import com.ja.util.DateUtil;
@Service("agencyCenter")
public class AgencyCenterSevicelmpl implements AgencyCenterSevice{
	
	
	@Autowired
	public UserMapper userMapper;
	
	@Autowired
	private DamalMapper damalMapper;
	
	@Autowired
	private LuckyCountMapper luckyCountMapper;
	
	@Autowired
	private AgencyCenterMapper agencyCenterMapper;
	
	@Override
	//实现代理给下级开户
	//成功则放回1  失败则返回0 返回2则参数不对  返回3则用户名已存在 返回4代表 赔率格式传输错误 5超过了平台规定的最低赔率 6用户名已经存在
	public int openAccount(User user, User u,String odds) {
		if(u == null || odds == null) {
			return 2;
		}
		if(u.getName() == null || "".equals(u.getName()) || "".equals(u.getPass()) || u.getPass() == null || u.getGamePlayer() == null) {
			return 2;
		}
		if(user.getGamePlayer() != null) {
			if(user.getGamePlayer() == 0) {
				return 7;//玩家账号不能成为代理  并且不能给下级玩家开户
			}
		}
		 User ur = userMapper.checkUser(u.getName());
		 if(ur != null) {
			 return 6;//用户名已经存在
		 }
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 NumberFormat nf= NumberFormat.getPercentInstance();//NumberFormat是一个工厂，可以直接getXXX创建，而getPercentInstance() 是返回当前默认语言环境的百分比格式。
		try {
			//查看赔率是否正确
			Number m=nf.parse(odds);
			DecimalFormat df = new DecimalFormat("#0.00000");
			String str = df.format(m);
			if(Integer.parseInt(WebsiteStateConfig.configs.get("agent_flag")) == 2) {
				if(user != null) {
					if(user.getOdds() != null) {//如果上级设置了他的赔率 那么就要判断如果他设置的赔率大于他上级的 给他设置的赔率则return 掉
						if(Double.parseDouble(str) <= user.getRemainder()) {
							u.setOdds(Double.parseDouble(str));//设置下级的赔率
							u.setRemainder(user.getRemainder()-Double.parseDouble(str));//设置自己还能调多少赔率
							if(user.getRemainder()-Double.parseDouble(str) <= 0) {
								u.setGamePlayer(0);
							}
						}else {
							return 3;
						}
					}else {
						if(Double.parseDouble(str) <= Double.parseDouble(WebsiteStateConfig.configs.get("minimumOdds"))) {
							u.setOdds(Double.parseDouble(str));//设置下级的赔率
							u.setRemainder(user.getRemainder()-Double.parseDouble(str));//设置自己还能调多少赔率
							if(user.getRemainder()-Double.parseDouble(str) <= 0) {//如果上级直接吃掉平台全部的  那这个用户只能为玩家
								u.setGamePlayer(0);
							}
						}else {
							return 3;
						}
					}
				}
			}
			//对密码加密
			String md5 = DigestUtils.md5DigestAsHex(u.getPass().getBytes());
			String pwd = DigestUtils.md5DigestAsHex(md5.getBytes());
			u.setPass(pwd);
			u.setNicheng(u.getName());
			u.setAvatar("img/user.jpg");
			u.setBalance(Double.parseDouble(WebsiteStateConfig.configs.get("huiyuanchushijine")));
			u.setFid(user.getId());//设置上级代理
			u.setRegisterTime(sdf.format(new Date()));
			u.setLastTime(sdf.format(new Date()));
			u.setNotTime("未登录0天");
			u.setState(1);
			u.setVip("VIP1");
			int num = userMapper.register(u);

			/** 根据当前名称查询帐号信息 */
			User us = userMapper.checkUser(u.getName());
			// 打码
			Damal damal = new Damal();
			damal.setHuiyuanzh(us.getName());
			damal.setCreatetime(us.getCreatetime());
			damal.setTikuansx(0.00);
			damal.setUserid(us.getId());
			damalMapper.addamal(damal);
			
			//幸运抽奖
			LuckyCount counts = new LuckyCount();
			counts.setName( us.getName());
			counts.setCount(0);
			counts.setCreateTime(DateUtil.getCurrTime());
			counts.setUserid(us.getId());
			luckyCountMapper.addLuckyCount(counts);
			return num;
		} catch (ParseException e) {
			return 4;
		}
	}

	@Override
	public List<AgentLink> pueryProxyLinks(String userName,Integer gamePlayer) {
		return agencyCenterMapper.pueryProxyLinks(userName,gamePlayer);
	}

	@Override
	public int insertProxyLinks(User user, HttpServletRequest request,String odds,Integer gamePlayer) {
		User u = userMapper.checkUser(user.getName());
		if(user.getState() == 2) {
			return 4;
		}
		if(u.getGamePlayer() != null) {
			if(u.getGamePlayer() == 0) {
				return 5; //玩家账号不能成为代理  并且不能生成代理连接以及邀请码
			}
		}
		if(odds == null || "".equals(odds)) {
			return 6;
		}
		String domain = "";
		AgentLink a = new AgentLink();
		if(request.getScheme() != null && !"".equals(request.getScheme())) {
			if ("http".equals(request.getScheme()) || "https".equals(request.getScheme())) {
				domain = "http://"+request.getServerName();//获取当前域名，
			}
		}
		Integer agencyId = agencyCenterMapper.agencyId();
		if(agencyId == null) {
			agencyId = 0;
		}
		String uid = new SimpleDateFormat("ss").format(new Date())+agencyId;//生成邀请码
		a.setiCode(domain + "?ref_code=" + uid);//代理连接
		a.setGamePlayer(gamePlayer);//代理还是玩家  0-玩家   1-代理    这个是第二套代理系统的 不要乱改
		try {
			NumberFormat nf= NumberFormat.getPercentInstance();	//将百分比转成 数字
			Number m=nf.parse(odds);
			DecimalFormat df = new DecimalFormat("#0.00000");
			String str = df.format(m);
			if(u.getOdds() != null) {//如果上级设置了他的赔率 那么就要判断如果他设置的赔率大于他上级的 给他设置的赔率则return 掉
				if(u.getRemainder() != null) {
					if(Double.parseDouble(str) <= u.getRemainder()) {
						a.setInferiorOdds(Double.parseDouble(str));//设置下级的赔率
					}else {
						return 3;
					}
				}
			}else {
				if(Double.parseDouble(str) <= Double.parseDouble(WebsiteStateConfig.configs.get("minimumOdds"))) {
					a.setInferiorOdds(Double.parseDouble(str));//设置下级的赔率
				}else {
					return 3;
				}
			}
		} catch (ParseException e) {
			return 2;
		}
		a.setUserName(user.getName());//设置代理名称
		a.setInvitationCode(uid);
		a.setUserId(user.getId());
		return agencyCenterMapper.insertProxyLinks(a);
	}

	@Override
	public Integer agencyId() {
		return agencyCenterMapper.agencyId();
	}

	@Override
	public List<Order> xjcathecticRecord(Integer startIndex, Integer lineCount,User user,String xname, Integer state, String cname, String date1,
			String date2) {
		if(xname != null && !"".equals(xname)) {
			User subordinate = userMapper.checkUser(xname);
			if(subordinate != null) {
				if(treeData(user,subordinate.getFid())) {
					return agencyCenterMapper.xjcathecticRecord(startIndex,lineCount,user.getName(), null, xname, state, cname, date1, date2);//进来说明是他下级
				}else {
					return new ArrayList<>();//没有查询到相关的
				}
			}
			return new ArrayList<>();//没有查询到相关的
		}else {
			return agencyCenterMapper.xjcathecticRecord(startIndex,lineCount,user.getName(), user.getId(), xname, state, cname, date1, date2);//进来说明是他下级
		}
	}

	@Override
	public boolean treeData(User u,int Fid) {
		User user = agencyCenterMapper.treeData(Fid);//查询他的上级
		while(true) {
			if(user != null) {
				if((int)u.getId() == (int)user.getId()) {
					return true;//查询到上级返回上级
				}else {
					user = agencyCenterMapper.treeData(user.getFid());//查询他的上级
				}
			}else {
				return false;//没有查询到上级
			}
		}
	}

	@Override
	public Integer xjcathecticRecords(User user,String xname,Integer state,String cname,String date1,String date2){
		if(xname != null && !"".equals(xname)) {
			User subordinate = userMapper.checkUser(xname);
			if(subordinate != null) {
				if(treeData(user,subordinate.getFid())) {
					return agencyCenterMapper.xjcathecticRecords(user.getName(), null, xname, state, cname, date1, date2);//进来说明是他下级
				}else {
					return 0;//没有查询到相关的
				}
			}
			return 0;//没有这个用户
		}else {
			return agencyCenterMapper.xjcathecticRecords(user.getName(), user.getId(), xname, state, cname, date1, date2);//进来说明是他下级
		}
	}

	@Override
	public List<User> subordinate(User u, String name,String cname) {
		if(name == null || "".equals(name)) {
			if(cname == null || "".equals(cname)) {
				//直接查询他的下级
				return agencyCenterMapper.subordinate(u);
			}
			//查询他下级的下级
			User user = userMapper.checkUser(cname);//查询当前用户的信息
			if(treeData(u,user.getFid())) {//验证是否是他下面的下级
				return agencyCenterMapper.subordinate(user);
			}
		}
		//根据用户名查询
		User subordinate = userMapper.checkUser(name);//查询当前用户的信息
		if(subordinate != null){
			if(treeData(u,subordinate.getFid())) {//验证是否是他的下级
				List<User> list = new ArrayList<User>();
				list.add(subordinate);
				return list;
			}
		}
		return new ArrayList<User>();
	}

	@Override
	public PagingData subordinatePipeline(PagingData paging,User u, String name,String cname, Integer state, String date1, String date2) {
		if(name != null && !"".equals(name)) {//根据会员名搜索下级的 记录
			//根据会员名搜索下级账户流水  充值提现  记录
			User user = userMapper.checkUser(name);//查询当前用户的信息
			if(user != null) {
				if(treeData(u,user.getFid())) {
					if(state != null) {
						if(state == 0) { //等于0 查询 账户流水  等于别的 就是查询 充值提现的记录
							//查询账户流水
							paging.setAllCount(agencyCenterMapper.subordinatePipelines(name, date1, date2));
							paging.setList(agencyCenterMapper.subordinatePipeline(name, paging.getStartIndex(), paging.getLineCount(), date1, date2));
							return paging;
						}
					}
					//查询充值提现 记录
					paging.setAllCount(agencyCenterMapper.subordinateRecharges(name, date1, date2, state));
					paging.setList(agencyCenterMapper.subordinateRecharge(paging.getStartIndex(), paging.getLineCount(), name, date1, date2, state));
					return paging;				
				}
			}
			return paging;//没有这个用户直接返回空
		}
		if(cname != null && !"".equals(cname)) {//查询某个代理下面的全部下级记录
			User user = userMapper.checkUser(cname);//查询当前用户的信息
			if(user != null) {
				if(treeData(u,user.getFid())) {//验证输入的这个代理是不是属于他下级
					if(state != null) {
						if(state == 0) {//直属下级的账户流水 充值提现 记录
							//查询账户流水
							paging.setAllCount(agencyCenterMapper.directlyUnders(user.getId(), date1, date2));
							paging.setList(agencyCenterMapper.directlyUnder(paging.getStartIndex(), paging.getLineCount(), user.getId(), date1, date2));
							return paging;
						}
					}
					//查询 充值提现 记录
					paging.setAllCount(agencyCenterMapper.rechargeWithdrawals(user.getId(), date1, date2, state));
					paging.setList(agencyCenterMapper.rechargeWithdrawal(paging.getStartIndex(), paging.getLineCount(), user.getId(), date1, date2, state));
					return paging;
				}
			}
			return paging;//没有这个用户直接返回空
		}
		if(state != null) {
			if(state == 0) {//直属下级的账户流水 充值提现 记录
				//查询账户流水
				paging.setAllCount(agencyCenterMapper.directlyUnders(u.getId(), date1, date2));
				paging.setList(agencyCenterMapper.directlyUnder(paging.getStartIndex(), paging.getLineCount(), u.getId(), date1, date2));
				return paging;
			}
		}
		//查询 充值提现 记录
		paging.setAllCount(agencyCenterMapper.rechargeWithdrawals(u.getId(), date1, date2, state));
		paging.setList(agencyCenterMapper.rechargeWithdrawal(paging.getStartIndex(), paging.getLineCount(), u.getId(), date1, date2, state));
		return paging;
	}

	@Override
	public int deleteAgenLink(User u, String invitationCode) {
		return agencyCenterMapper.deleteAgenLink(u, invitationCode);
	}

	@Override
	public List<User> treeDataobject(int Fid) {
		List<User> list = new ArrayList<User>();
		User user = agencyCenterMapper.treeData(Fid);//查询他的上级
		while(true) {
			if(user != null) {
				list.add(user);
				user = agencyCenterMapper.treeData(user.getFid());//查询他的上级
			}else {
				return list; 
			}
		}
	}

	@Override
	public AgentLink pueryagencyInvitationCode(String invitationCode) {
		return agencyCenterMapper.pueryagencyInvitationCode(invitationCode);
	}
}
